package br.com.emvista.model.dao.base;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

public class DAO<T>{

	private Class<T> entityClass = null;
	
	public DAO(Class<T> enityClass){
		this.entityClass = enityClass;
		
	}
	
	public void inserir(T entidade) {
		
		EntityManager em = EntityManagerHelper.getEntityManager();
		EntityTransaction t = em.getTransaction();
		try {
			
			t.begin();
			em.persist(entidade);
			t.commit();
			
		} catch (Exception e) {
			
			e.printStackTrace();
			if (t.isActive()) t.rollback();
			
		} finally {
			
			em.close();
			
		}
		
	}
	
	public void atualizar(T entidade) {
		
		EntityManager em = EntityManagerHelper.getEntityManager();
		EntityTransaction t = em.getTransaction();
		try {
			
			t.begin();
			em.merge(entidade);
			t.commit();
			
		} catch (Exception e) {
			
			e.printStackTrace();
			if (t.isActive()) t.rollback();
			
		} finally {
			
			em.close();
			
		}
		
	}

	public void remover(Object id) {
		
		EntityManager em = EntityManagerHelper.getEntityManager();
		EntityTransaction t = em.getTransaction();
		try {
			
			t.begin();
			T e = (T) em.find(entityClass, id);
			em.remove(e);
			t.commit();
			
		} catch (Exception e) {
			
			e.printStackTrace();
			if (t.isActive()) t.rollback();
			
		} finally {
			
			em.close();
			
		}
		
	}

	public T localizar(Object id){
		
		EntityManager em = EntityManagerHelper.getEntityManager();
		try {
			return (T) em.find(entityClass, id);
		} finally {
			em.close();
		}
	}
	
	
	
}
